package czx.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import czx.dao.BaseDaoI;
import czx.util.HqlExp;

@SuppressWarnings({ "unchecked" })
@Repository("baseDao")
public class BaseDaoImpl<T> implements BaseDaoI<T> {
	private SessionFactory sessionFactory;

	private Session getCurrentSession() {
		return this.sessionFactory.getCurrentSession();
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public Serializable save(T t) {
		return sessionFactory.getCurrentSession().save(t);
	}

	@Override
	public List<T> find(HqlExp hqlExp) {
		List<T> l = new ArrayList<T>();
		if (hqlExp != null) {
			Query q = getCurrentSession().createQuery(hqlExp.getHql());
			Map<String, Object> m = hqlExp.getParams();
			if (m != null && !m.isEmpty()) {
				for (String key : m.keySet()) {
					q.setParameter(key, m.get(key));
				}
			}
			if (hqlExp.getPageSize() > 0) {
				q.setFirstResult(hqlExp.getFirstResult());
				q.setMaxResults(hqlExp.getPageSize());
			}

			l = q.list();
		}

		return l;
	}

	@Override
	public T get(HqlExp hqlExp) {
		if (hqlExp != null) {
			Query q = getCurrentSession().createQuery(hqlExp.getHql());
			Map<String, Object> m = hqlExp.getParams();
			if (m != null && !m.isEmpty()) {
				for (String key : m.keySet()) {
					q.setParameter(key, m.get(key));
				}
			}
			q.setFirstResult(0);
			q.setMaxResults(1);

			return (T) q.uniqueResult();
		}

		return null;
	}

	@Override
	public T get(Class<T> c, Serializable id) {
		return (T) this.getCurrentSession().get(c, id);
	}

	@Override
	public void update(T t) {
		getCurrentSession().update(t);
	}

	@Override
	public void delete(T t) {
		getCurrentSession().delete(t);
	}

	@Override
	public void saveOrUpdate(T t) {
		getCurrentSession().saveOrUpdate(t);
	}

	@Override
	public Long count(HqlExp hqlExp) {
		if (hqlExp == null) {
			return 0L;
		} else {
			Query q = getCurrentSession().createQuery(hqlExp.getCountHql());
			Map<String, Object> m = hqlExp.getParams();
			if (m != null && !m.isEmpty()) {
				for (String key : m.keySet()) {
					q.setParameter(key, m.get(key));
				}
			}

			return (Long) q.uniqueResult();
		}
	}
}
